Default Struct Builder
Generates builder methods of every field of a struct. It is meant to be used on structs that
implement Default
. There is no separate builder struct generated and no need to call a
build()
method at the end or .unwrap()
.
This crate is used by the crate leptos-use
for the option structs that
can be passed to the various functions.
Installation
In your project folder run
Usage
It is very easy to use:
use DefaultBuilder;
you can then use the struct like this:
let options = default.offset;
assert_eq!;
assert_eq!;
assert_eq!;
Generics
The macro is ready to be used on generic structs.
use DefaultBuilder;
Doc comments
All doc comments on fields are directly passed on to their generated setter methods.
How it works
The derive macro generates the following code:
Generics
In the case of a generic field the generated method is a bit more complex because by calling the method the type of the type parameter can be different than before.
Let's look at the following example.
use DefaultBuilder;
This generates the setter method below.
In cases where you don't want a generic field to be able to change the generic type you
can annotate it with keep_type
.
this will generate a standard builder method as if T
wasn't generic.
Box
, Rc
and Arc
The macro detects if a field is a Box
(or Rc
or Arc
) and generates a builder method that
accepts the inner type (without Box
or Rc
or Arc
) and adds the outer type in the body.
In case it's a Box<dyn Trait>
the builder method will have an argument of type
impl Trait
. The same goes for Rc
and Arc
.
If you want to prevent this auto un-wrapping you can use the #[builder(keep_outer)]
attribute.
This will generate the following code:
Related Work
For more general purposes please check out the much more powerful
derive_builder
crate.